# -*- coding: utf-8 -*-
# Tests for tag support, both on model and form levels

from unittest import TestCase

from stream.formfields import SeparatedStringsField, ModelSeparatedStringsField
from stream.models import *
from stream.utils import unorderedEqual
from base import FilledDbTestCase

class SeparatedStringsFieldTest(TestCase):
    def testClean(self):
        field = SeparatedStringsField()
        strings_list = field.clean("  this    is  a    string ")
        self.assertEqual(strings_list, ["this", "is", "a", "string"])

    def testNonalphaTag(self):
        field = SeparatedStringsField()
        self.assertEqual(['c++'], field.clean('c++'))

    def testKeywordPassing(self):
        label = 'text'
        field = SeparatedStringsField(label = label)
        self.assertEqual(field.label, label)

class StringFieldsTest(FilledDbTestCase):
    """
    Tests for ModelSeparatedStringsField
    """
    def setUp(self):
        super(StringFieldsTest, self).setUp()
        self.tag_field = ModelSeparatedStringsField(Tag, 'name')

    def commonTagTest(self, name_list):
        tag_list = self.tag_field.clean(' '.join(name_list))
        self.assertTrue(unorderedEqual(name_list, map(lambda x: x.name, tag_list)))
        return tag_list

    def testExistingTagsAddition(self):
        tag_count = Tag.objects.count()
        name_list = ["yahoo", "search"]
        self.commonTagTest(name_list)
        new_tag_count = Tag.objects.count()
        self.assertEqual(tag_count, new_tag_count)

    def testNewTagsAddition(self):
        name_list = ["new", "tags"]
        added_tag_list = self.commonTagTest(name_list)
        # Check they are in db now
        for name in name_list:
            self.assertEqual(Tag.objects.filter(name=name).count(), 1)

    def testKeywordPassing(self):
        # TODO: this is copypasted
        label = 'text'
        field = ModelSeparatedStringsField(Tag, 'name', label = label)
        self.assertEqual(field.label, label)
